<template>
  <div class="workspace-panel">
    <!-- 头部区域 -->
    <div class="workspace-header">
      <div class="header-left">
        <h2>工作台概览</h2>
        <p class="header-subtitle">实时数据监控与业务分析</p>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button :type="timeRange === '7d' ? 'primary' : 'default'" @click="setTimeRange('7d')">
            近7天
          </el-button>
          <el-button :type="timeRange === '30d' ? 'primary' : 'default'" @click="setTimeRange('30d')">
            近30天
          </el-button>
          <el-button :type="timeRange === '90d' ? 'primary' : 'default'" @click="setTimeRange('90d')">
            近90天
          </el-button>
        </el-button-group>
        <el-button type="primary" :icon="RefreshRight" @click="refreshData" :loading="loading">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-grid">
      <StatCard
        v-for="stat in statsData"
        :key="stat.key"
        :value="stat.value"
        :label="stat.label"
        :icon="stat.icon"
        :type="stat.type"
        :unit="stat.unit"
        :trend="stat.trend"
        :chart-data="stat.chartData"
        :loading="loading"
        :show-action="true"
        @action="handleStatAction"
      />
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 用户增长趋势 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>用户增长趋势</span>
            <el-dropdown @command="handleUserChartCommand">
              <el-button type="text">
                更多 <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="export">导出数据</el-dropdown-item>
                  <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
        <BaseChart :option="userGrowthOption" height="300px" />
      </el-card>

      <!-- 系统性能监控 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>系统性能监控</span>
            <el-tag :type="systemHealth.type" size="small">{{ systemHealth.text }}</el-tag>
          </div>
        </template>
        <BaseChart :option="systemPerformanceOption" height="300px" />
      </el-card>

      <!-- 业务数据分布 -->
      <el-card class="chart-card chart-card--full">
        <template #header>
          <div class="chart-header">
            <span>业务数据分布</span>
            <div class="chart-controls">
              <el-select v-model="businessDataType" size="small" style="width: 120px">
                <el-option label="按地区" value="region" />
                <el-option label="按类型" value="type" />
                <el-option label="按状态" value="status" />
              </el-select>
            </div>
          </div>
        </template>
        <div class="chart-container--horizontal">
          <BaseChart :option="businessDistributionOption" height="350px" width="60%" />
          <div class="chart-legend">
            <div class="legend-title">数据统计</div>
            <div class="legend-items">
              <div v-for="item in businessLegend" :key="item.name" class="legend-item">
                <div class="legend-color" :style="{ backgroundColor: item.color }"></div>
                <div class="legend-info">
                  <div class="legend-name">{{ item.name }}</div>
                  <div class="legend-value">{{ item.value }} ({{ item.percentage }}%)</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 实时数据流 -->
    <div class="realtime-section">
      <el-card>
        <template #header>
          <div class="chart-header">
            <span>实时数据流</span>
            <div class="realtime-status">
              <div class="status-indicator" :class="{ 'status-indicator--active': realtimeConnected }"></div>
              <span>{{ realtimeConnected ? '已连接' : '未连接' }}</span>
            </div>
          </div>
        </template>
        <div class="realtime-grid">
          <div v-for="metric in realtimeMetrics" :key="metric.key" class="realtime-metric">
            <div class="metric-header">
              <el-icon :color="metric.color"><component :is="metric.icon" /></el-icon>
              <span class="metric-name">{{ metric.name }}</span>
            </div>
            <div class="metric-value" :style="{ color: metric.color }">
              {{ metric.value }}
              <span class="metric-unit">{{ metric.unit }}</span>
            </div>
            <div class="metric-trend">
              <el-icon :color="metric.trend > 0 ? '#67C23A' : '#F56C6C'">
                <ArrowUp v-if="metric.trend > 0" />
                <ArrowDown v-else />
              </el-icon>
              <span :style="{ color: metric.trend > 0 ? '#67C23A' : '#F56C6C' }">
                {{ Math.abs(metric.trend) }}%
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { RefreshRight, ArrowDown, ArrowUp, Monitor, User, DataAnalysis, Connection } from '@element-plus/icons-vue'
import BaseChart from './charts/BaseChart.vue'
import StatCard from './charts/StatCard.vue'
import { analyticsApi } from '@/api'

// 响应式数据
const loading = ref(false)
const timeRange = ref('7d')
const businessDataType = ref('region')
const realtimeConnected = ref(false)

// 统计数据
const statsData = ref([
  {
    key: 'users',
    value: 12580,
    label: '总用户数',
    icon: User,
    type: 'primary',
    unit: '人',
    trend: { type: 'up', value: 12.5, label: '较昨日' },
    chartData: [120, 132, 101, 134, 90, 230, 210]
  },
  {
    key: 'orders',
    value: 3456,
    label: '今日订单',
    icon: DataAnalysis,
    type: 'success',
    unit: '笔',
    trend: { type: 'up', value: 8.3, label: '较昨日' },
    chartData: [80, 92, 101, 74, 90, 130, 140]
  },
  {
    key: 'revenue',
    value: '¥185,430',
    label: '今日收入',
    icon: 'Money',
    type: 'warning',
    trend: { type: 'down', value: 3.2, label: '较昨日' },
    chartData: [100, 120, 90, 150, 80, 110, 95]
  },
  {
    key: 'performance',
    value: 98.5,
    label: '系统性能',
    icon: Monitor,
    type: 'info',
    unit: '%',
    trend: { type: 'up', value: 1.8, label: '较昨日' },
    chartData: [95, 97, 98, 96, 99, 98, 99]
  }
])

// 系统健康状态
const systemHealth = ref({
  type: 'success',
  text: '运行正常'
})

// 实时指标
const realtimeMetrics = ref([
  {
    key: 'online',
    name: '在线用户',
    value: 1234,
    unit: '人',
    color: '#409EFF',
    icon: User,
    trend: 5.2
  },
  {
    key: 'requests',
    name: '每秒请求',
    value: 856,
    unit: 'req/s',
    color: '#67C23A',
    icon: Connection,
    trend: -2.1
  },
  {
    key: 'response',
    name: '响应时间',
    value: 234,
    unit: 'ms',
    color: '#E6A23C',
    icon: Monitor,
    trend: 1.8
  },
  {
    key: 'error',
    name: '错误率',
    value: 0.05,
    unit: '%',
    color: '#F56C6C',
    icon: 'Warning',
    trend: -0.3
  }
])

// 图表配置
const userGrowthOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'cross' }
  },
  legend: {
    data: ['新增用户', '活跃用户']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['01-01', '01-02', '01-03', '01-04', '01-05', '01-06', '01-07']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '新增用户',
      type: 'line',
      stack: 'Total',
      smooth: true,
      data: [120, 132, 101, 134, 90, 230, 210],
      itemStyle: { color: '#409EFF' }
    },
    {
      name: '活跃用户',
      type: 'line',
      stack: 'Total',
      smooth: true,
      data: [220, 182, 191, 234, 290, 330, 310],
      itemStyle: { color: '#67C23A' }
    }
  ]
})

const systemPerformanceOption = ref({
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      return params.map(param => 
        `${param.seriesName}: ${param.value}%`
      ).join('<br/>')
    }
  },
  legend: {
    data: ['CPU使用率', '内存使用率', '磁盘使用率']
  },
  radar: {
    indicator: [
      { name: 'CPU', max: 100 },
      { name: '内存', max: 100 },
      { name: '磁盘', max: 100 },
      { name: '网络', max: 100 },
      { name: '负载', max: 100 }
    ]
  },
  series: [{
    name: '系统性能',
    type: 'radar',
    data: [
      {
        value: [65, 78, 45, 82, 56],
        name: '当前状态',
        itemStyle: { color: '#409EFF' }
      }
    ]
  }]
})

const businessDistributionOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  series: [{
    name: '业务分布',
    type: 'pie',
    radius: ['40%', '70%'],
    avoidLabelOverlap: false,
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    },
    data: [
      { value: 1048, name: '华东地区' },
      { value: 735, name: '华南地区' },
      { value: 580, name: '华北地区' },
      { value: 484, name: '西南地区' },
      { value: 300, name: '其他地区' }
    ]
  }]
})

// 业务图例数据
const businessLegend = ref([
  { name: '华东地区', value: 1048, color: '#409EFF', percentage: 33.2 },
  { name: '华南地区', value: 735, color: '#67C23A', percentage: 23.3 },
  { name: '华北地区', value: 580, color: '#E6A23C', percentage: 18.4 },
  { name: '西南地区', value: 484, color: '#F56C6C', percentage: 15.3 },
  { name: '其他地区', value: 300, color: '#909399', percentage: 9.8 }
])

// 方法
const setTimeRange = (range) => {
  timeRange.value = range
  refreshData()
}

const refreshData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里可以调用实际的API
    // const data = await analyticsApi.getDashboardData(timeRange.value)
    
    console.log('刷新数据完成')
  } catch (error) {
    console.error('刷新数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleStatAction = (stat) => {
  console.log('查看统计详情:', stat)
}

const handleUserChartCommand = (command) => {
  console.log('用户图表操作:', command)
}

// 模拟实时数据连接
let realtimeInterval = null

const startRealTimeData = () => {
  realtimeConnected.value = true
  realtimeInterval = setInterval(() => {
    // 模拟实时数据更新
    realtimeMetrics.value.forEach(metric => {
      const change = (Math.random() - 0.5) * 10
      metric.value = Math.max(0, Math.floor(metric.value + change))
      metric.trend = change
    })
  }, 3000)
}

const stopRealTimeData = () => {
  realtimeConnected.value = false
  if (realtimeInterval) {
    clearInterval(realtimeInterval)
    realtimeInterval = null
  }
}

onMounted(() => {
  refreshData()
  startRealTimeData()
})

onUnmounted(() => {
  stopRealTimeData()
})
</script>

<style scoped>
.workspace-panel {
  padding: 0;
}

.workspace-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.chart-card--full {
  grid-column: span 2;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-container--horizontal {
  display: flex;
  align-items: flex-start;
  gap: 24px;
}

.chart-legend {
  flex: 1;
  padding: 20px 0;
}

.legend-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.legend-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s ease;
}

.legend-item:hover {
  background-color: #f8f9fa;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.legend-info {
  flex: 1;
}

.legend-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
}

.legend-value {
  font-size: 12px;
  color: #909399;
}

.realtime-section {
  margin-bottom: 24px;
}

.realtime-status {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #F56C6C;
  animation: pulse 2s infinite;
}

.status-indicator--active {
  background-color: #67C23A;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.realtime-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.realtime-metric {
  padding: 16px;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  border-radius: 8px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.realtime-metric:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.metric-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.metric-name {
  font-size: 12px;
  color: #606266;
}

.metric-value {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
}

.metric-unit {
  font-size: 12px;
  font-weight: 400;
  opacity: 0.7;
}

.metric-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-card--full {
    grid-column: span 1;
  }
  
  .chart-container--horizontal {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .workspace-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .realtime-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}
</style>
